import axios from 'axios'
// import Vue from 'vue'
import loading from '@/modules/preloader-full/preloader-full'
// import toast from '@/modules/popup/msg-simple'

export default class AjaxGeneral {
  constructor (dataHandle, ax = axios) {
    if (dataHandle) {
      this.dataHandle = dataHandle
    } else {
      this.dataHandle = function (data, config) {
        if (data.status === 200) {
          return data.result
        }
        return new Error(config.url + ' : ' + data.message)
      }
    }
    this.axios = ax
  }
  request (config) {
    let { hasLoading = true } = config
    if (hasLoading) loading.show()
    if (process.env.NODE_ENV !== 'production') {
      Object.assign(config, {
        baseURL: require('@/mock.config.js').default.baseUrl
      })
    }
    return this.axios.request(config).then(({ data }) => {
      const result = this.dataHandle(data, config)
      // 失败情况
      if (result instanceof Error) {
        return Promise.reject(result)
      }
      // 成功情况
      if (hasLoading) loading.close()
      return result
    }).catch(e => {
      if (hasLoading) loading.close()
      // toast.error(e.message)
      return Promise.reject(e)
    })
  }
  get (url, config = {}) {
    config.method = 'get'
    config.url = url
    return this.request(config)
  }
  post (url, data, config = {}) {
    config.method = 'post'
    config.url = url
    config.data = data
    return this.request(config)
  }
}

// asp.net 后台返回用
// export const ajaxNet = new AjaxGeneral(function (data) {
//   if (data.code === 0) {
//     return data.data
//   }
//   return new Error(data.message)
// })

// 默认 go
// export default new AjaxGeneral()
